class Solution {
    public boolean canThreePartsEqualSum(int[] A) {
        int sum = 0;
        for (int value : A) {
            sum += value;
        }
        if (sum % 3 != 0) {
            return false;
        }
        int left = 0;
        int right = A.length - 1;
        int leftSum = A[left];
        int rightSum = A[right];
        int avg = sum / 3;
        while (left < right) {
            printArr(A, left, right);
            if ((leftSum == avg) && (rightSum == avg)) {
                return right - left > 1;
            }
            if (leftSum != avg) {
                leftSum += A[++left];
            }
            if (rightSum != avg) {
                rightSum += A[--right];
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] arr = {1, -1, 1, -1};
        boolean res = new Solution().canThreePartsEqualSum(arr);
        System.out.println(res);
    }

    private void printArr(int[] arr, Integer left, Integer right) {
        if (arr == null || arr.length == 0) return;
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        for (int i = 0; i < arr.length; i++) {
            if (left != null && left.equals(i) || right != null && right.equals(i)) {
                sb.append("[").append(arr[i]).append("]");
            } else {
                sb.append(" ").append(arr[i]).append(" ");
            }
        }
        sb.append("}");
        System.out.println(sb);
    }
}